package com.cnsecloud.config;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Enumeration;
import java.util.Map;

/**
 * @Author:HYZ
 * @Date:2023-3-21
 */
public class LicenseUtil {

    public static final String KEY_ALGORITHM = "RSA";

    private static final String PUBLIC_KEY = "RSAPublicKey";

    private static final String PRIVATE_KEY = "RSAPrivateKey";


    public static String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ6cyIwk/DrmsW4WSNGyvU9qVxan9K9FqHed6Gs/2C8xAQTs/4y3klB5u/tKgXbOIh2EnnaY67QlayKGb8mbwDMuFJhMT6GOajCuYUSdGBhNIOnc+7Zs9TZn7XLyRdFfjiZ+m+5/hNL2OlN+aGdNEaoJbM8trPJYYk+6FaUA1PTwIDAQAB";
    public static String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAInpzIjCT8OuaxbhZI0bK9T2pXFqf0r0Wod53oaz/YLzEBBOz/jLeSUHm7+0qBds4iHYSedpjrtCVrIoZvyZvAMy4UmExPoY5qMK5hRJ0YGE0g6dz7tmz1NmftcvJF0V+OJn6b7n+E0vY6U35oZ00Rqglszy2s8lhiT7oVpQDU9PAgMBAAECgYB9PAm3xnuYPjKQvGwKlrne0Xq62vJspifvDgO8XoW+++mCZY8FZf/EWHxeQTbCzuUpxraVpY0vDrabYYTjrNbE13V+mP/lqeCJBo0lqRJcLH4/KhmVvOpQJ6m+8AWZ/2/VAlObrCECgz7GSHDAohWFN6NvWwgNcIWqvfSW6Q+3gQJBANt77rNod36JKSEgjYnK+HZ5r8OwYP5y3hauhfjHaVkDwRE50W8H4Yypv7GBhBRlI2su9Qn3in82QnU4HZtQ3tkCQQCg260Ayg2f8qUj3nU0/vnvtP7E0UUuX+mESSXptI861VAzPSsJ77QgQpRQKdkr++KBCwkGJD0B6B1sxq66JRZnAkA3SDjwUWC/q1aDtIpR6aC5Xp8JwBQ+IrqTpfOynK+JLyvi5dg9ihOidWMGF6Qn6u2H4rTvhL0Km6UTl0XFyBHJAkAyPswYXgTJfGqW/KrRxf9eH8QgyFl6tdzkRFECYjMHJpBpoOarsOMr3IAlVh0O/xvuQPstnu4rhUyDqL/1RxZrAkEAiziMQnC1cf/dJziIv0+MGS1dPDrW1dpJsNsXCvGEa9ykNBTQVJCwA7uoKbEGKwoIw+SBGOdHn2zZ4TWiLoWW7A==";

    // public static String macIp = "D8-BB-C1-BF-43-C3"; // 220
    public static String macIp = "02-42-AF-12-B1-67"; // 121
    // public static String macIp = "02-42-28-1B-96-A0"; // 116
    // public static String macIp = "52-54-00-91-5C-E7"; // 99
    // public static String macIp = "02-42-AC-11-00-08"; // 117


    public static void main(String[] args) {

        // macIp = getMacId();
        System.out.println(macIp);


        String s = creatLicenseSignData();
        System.out.println(s);
    }


    public static String creatLicenseSignData() {

        try {
            PrivateKey privateKey = getPrivateKey(privateKeyStr);

            Signature signature = Signature.getInstance("SHA256withRSA", new BouncyCastleProvider());
            signature.initSign(privateKey);
            signature.update(macIp.getBytes());
            byte[] sign = signature.sign();
            return Base64.getEncoder().encodeToString(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 此方法描述的是：获得服务器的MAC地址
     */
    public static String getMacId() {
        String macId = "";
        InetAddress ip = null;
        NetworkInterface ni = null;
        try {
            boolean bFindIP = false;
            Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
                .getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                if (bFindIP) {
                    break;
                }
                ni = (NetworkInterface) netInterfaces
                    .nextElement();
                // ----------特定情况，可以考虑用ni.getName判断
                // 遍历所有ip
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = (InetAddress) ips.nextElement();
                    if (!ip.isLoopbackAddress() // 非127.0.0.1
                        && ip.getHostAddress().matches(
                        "(\\d{1,3}\\.){3}\\d{1,3}")) {
                        bFindIP = true;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != ip) {
            try {
                macId = getMacFromBytes(ni.getHardwareAddress());
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return macId;
    }


    private static String getMacFromBytes(byte[] bytes) {
        StringBuffer mac = new StringBuffer();
        byte currentByte;
        boolean first = false;
        for (byte b : bytes) {
            if (first) {
                mac.append("-");
            }
            currentByte = (byte) ((b & 240) >> 4);
            mac.append(Integer.toHexString(currentByte));
            currentByte = (byte) (b & 15);
            mac.append(Integer.toHexString(currentByte));
            first = true;
        }
        return mac.toString().toUpperCase();
    }


    // 获取公钥字符串
    public static String getPublicKeyStr(Map<String, Object> keyMap) {
        // 获得 map 中的公钥对象，转为 key 对象
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        // 编码返回字符串
        return encryptBASE64(key.getEncoded());
    }

    // 获取私钥字符串
    public static String getPrivateKeyStr(Map<String, Object> keyMap) {
        // 获得 map 中的私钥对象，转为 key 对象
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        // 编码返回字符串
        return encryptBASE64(key.getEncoded());
    }

    // 获取公钥
    public static PublicKey getPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] publicKeyByte = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    // 获取私钥
    public static PrivateKey getPrivateKey(String privateKeyString) throws Exception {
        byte[] privateKeyByte = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyByte);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * BASE64 编码返回加密字符串
     *
     * @param key 需要编码的字节数组
     * @return 编码后的字符串
     */
    public static String encryptBASE64(byte[] key) {
        return new String(Base64.getEncoder().encode(key));
    }

    /**
     * BASE64 解码，返回字节数组
     *
     * @param key 待解码的字符串
     * @return 解码后的字节数组
     */
    public static byte[] decryptBASE64(String key) {
        return Base64.getDecoder().decode(key);
    }


}
